package com.zrf.testchatgpt.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zrf.testchatgpt.entity.Config;
import com.zrf.testchatgpt.mapper.ConfigMapper;
import com.zrf.testchatgpt.service.IConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrf.testchatgpt.constant.CacheConstants;
import com.zrf.testchatgpt.util.RedisCacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zrf
 * @since 2023-03-15
 */
@Service
public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, Config> implements IConfigService {

    @Autowired
    private ConfigMapper configMapper;
    @Autowired
    private RedisCacheUtil redisCacheUtil;
    @Override
    public String selectConfigByKey(String configKey) {
        String configValue = Convert.toStr(redisCacheUtil.getCacheObject(getCacheKey(configKey)));
        if (configValue!=null)
        {
            return configValue;
        }
//        Config config = new Config();
//        config.setConfigKey(configKey);
        LambdaQueryWrapper<Config> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Config::getConfigKey,configKey);
        Config retConfig = configMapper.selectOne(wrapper);
        if (retConfig!=null)
        {
            redisCacheUtil.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return "";
    }
    private String getCacheKey(String configKey)
    {
        return CacheConstants.SYS_CONFIG_KEY + configKey;
    }
}
